import { useState, useEffect } from "react";
import {
  Space,
  Tag,
  Pagination,
  Table,
  Button,
  Modal,
  Form,
  Input,
  Row,
  Col,
  Tree,
  message,
} from "antd";
import { getClass,postScore } from "../../api/teacher.js";

import { getClassStu } from "../../api/user";
// import {}
import Action from "../Action";
import { ArrowLeftOutlined } from "@ant-design/icons";
import { useAuth } from "../../context/AuthProvider";
import { useLocation } from "react-router-dom";
const timeOptions = [
  "第一节课",
  "第二节课",
  "第三节课",
  "第四节课",
  "第五节课",
  "第六节课",
  "第七节课",
  "第八节课",
  "第九节课",
];
const dayOptions = [
  "星期一",
  "星期二",
  "星期三",
  "星期四",
  "星期五",
  "星期六",
  "星期日",
];
const statusOptions = ["未开始", "课程中", "已结课"];
const Tstu = () => {
  const { user, deleteUser } = useAuth();
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [stuScore, setStuScoreList] = useState([]);
  const [stuData, setStuData] = useState({});
  const [allClass, setAllClass] = useState([]);
  const [selectdClass, setselectdClass] = useState([]);

  const [isShowContext, setIsShowContext] = useState(0);

  const [form] = Form.useForm();
  const [value, setValue] = useState();
  const location = useLocation();

  const onChange = (newValue) => {
    console.log(newValue);
    setValue(newValue);
  };
  const handleData = (data) => {
    // 处理回传的数据
    console.log(data);
    let list = [...stuScore];
    for (let i = 0; i < list.length; i++) {
      if (list[i].tid == data.tid) {
        list[i] = data;
        break;
      }
    }
    setStuScoreList(list);
  };
  const showModal = (e, record) => {
    console.log(record);
    setIsModalOpen(true);
    setStuData(record);
    form.setFieldsValue(record);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
  const showContext = (e, item, isShow) => {
    if (isShow) {
      setIsShowContext(0);
    } else {
      setIsShowContext(item.cid);
    }
  };
  const getStu = (e,item) => {
    setselectdClass(item)
    item.id=user.loginid
    getClassStu(item).then((res)=>{
      for (let i = 0; i < res.length; i++) {
        res[i].key = res[i].sid;
      }
      console.log(res, "getClassStu");
      setStuScoreList(res);
    })
  };
  // const [selectedTags, setSelectedTags] = useState('');
  // const [news, setNews] = useState([]);
  // // const [total, setTotal] = useState(0);
  // // const [page, setPage] = useState(1);

  useEffect(() => {
    getClass({ id: user.loginid, type: 1 }).then((res) => {
      const result = [];

      res.forEach((item, index) => {
        const existingItem = result.find((r) => r.classname === item.classname);
        if (existingItem) {
          existingItem.children.push(item);
        } else {
          result.push({
            classname: item.classname,
            cid: index + 1,
            children: [item],
          });
        }
      });
      console.log("result", result);
      setAllClass(result);
    });

    console.log(location);
    if (location.state) {
      getClassStu({ classname: location.state.classname }).then((res) => {
        for (let i = 0; i < res.length; i++) {
          res[i].key = res[i].sid;
        }
        console.log(res, "getClassStu");
        setStuScoreList(res);
      });
    }
  }, []);
  const onFinish = (values) => {
    console.log(values,stuData)
    let newStuData=stuData
    newStuData.dailyscore=values.dailyscore
    newStuData.testscore=values.testscore
    newStuData.tid=user.loginid

    setStuData(newStuData)
    console.log(user )
    postScore({newStuData,selectdClass}).then(res=>{
      if(res.status=="ok"){
        message.success("打分成功")
        setIsModalOpen(false);

      }
    })
  };
  const columns = [
    {
      title: "学号",
      dataIndex: "sid",
      key: "sid",
    },
    {
      title: "姓名",
      dataIndex: "sname",
      key: "sname",
    },
    {
      title: "所属学院",
      dataIndex: "ssub",
      key: "ssub",
    },

    {
      title: "Action",
      key: "action",

      render: (_, record) => (
        <a onClick={(e) => showModal(e, record)}>打分</a>
        //   <Space size="middle">
        //     <Action />
        //     <a onClick={showModal}>修改</a>
        //     <a  onClick={(e)=>deleteTeacher(e,record)}>删除{record.tid}</a>
        //   </Space>
      ),
    },
  ];

  return (
    <>
      {/* <div>
        <ArrowLeftOutlined />
      </div> */}
      <div
        style={{
          display: "flex",
          justifyContent: "space-around",
          width: "100%",
        }}
      >
        <div style={{ width: "30%" }}>
          <div style={{ overflow: "auto", height: "100%" }}>
            {allClass.map((item, index) => {
              return (
                // <a>
                <div
                  key={index + "allClass"}
                  style={{
                    border: "solid #ccc",
                    borderRadius: "12px",
                    margin: "auto",
                    width: "90%",
                    padding: "10px",
                    marginBottom: "10px",
                  }}
                >
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                    }}
                  >
                    <div>{item.classname}</div>
                    <Button
                      type="link"
                      onClick={(e) =>
                        showContext(e, item, isShowContext == item.cid)
                      }
                    >
                      {isShowContext == item.cid ? "收回" : "展开"}
                    </Button>
                  </div>
                  {isShowContext == item.cid && (
                    <div>
                      {item.children.map((item1, index1) => {
                        return (item1.status==2&&
                          <a  key={"context" + index1} onClick={e=>getStu(e,item1)}>
                          <div
                           
                            style={{
                              color:"black",
                              border: "2px",
                              borderBottomStyle: "solid",
                              width: "100%",
                              marginBottom: "10px",
                              display: "flex",
                              alignItems: "center",
                              justifyContent: "space-around",
                            }}
                          >
                            {/* <span>1</span>/ */}
                            <div>
                              <div>学年</div> <div>{item1.year}</div>
                            </div>
                            <span>
                              <div> {dayOptions[item1.day - 1]}</div>{" "}
                              <div>{timeOptions[item1.time - 1]}</div>
                            </span>

                            <span>
                              {" "}
                              <div>地点</div> <div>{item1.address}</div>
                            </span>
                            <span>
                              {item1.status == 0 && (
                                <Tag color="cyan">未开始</Tag>
                              )}
                              {item1.status == 1 && (
                                <Tag color="blue">课程中</Tag>
                              )}
                              {item1.status == 2 && (
                                <Tag color="green">已结课</Tag>
                              )}
                            </span>
                            <span>{">"}</span>
                          </div>
                          </a>
                        );
                      })}
                    </div>
                  )}
                </div>
                
              );
            })}
          </div>
        </div>
        {stuScore && (
          <Table
            style={{ width: "70%" }}
            dataSource={stuScore}
            columns={columns}
          />
        )}
      </div>
      <Modal
        title="学生打分"
        open={isModalOpen}
        footer={null}
        onCancel={handleCancel}
      >
        <Row gutter={16}>
          <Col className="gutter-row" span={12}>
            <div>学号：{stuData.sid}</div>
          </Col>
          <Col className="gutter-row" span={12}>
            <div>姓名: {stuData.sname}</div>
          </Col>
          <Col className="gutter-row" span={12}>
            <div>年级：{stuData.syear}</div>
          </Col>
          <Col className="gutter-row" span={12}>
            <div>所属学院：{stuData.ssub}</div>
          </Col>
        </Row>
        <hr />
        <Form
          name="basic"
          layout="vertical"
          // style={{ width: 400, margin: '50px auto' }}
          onFinish={onFinish}
          autoComplete="off"
          form={form}
          initialValues={stuData}
        >
          {/* <Form.Item
                        label="学号"
                        name="sid"
                        rules={[
                            {
                                required: true,
                                message: '请输入教工号',
                            },
                        ]}
                    >
                        <Input />
                    </Form.Item> */}

          <Row gutter={16}>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="课堂分数"
                name="dailyscore"
                rules={[
                  {
                    required: true,
                    message: "请输入课堂分数",
                  },
                ]}
              >
                <Input />
              </Form.Item>{" "}
            </Col>
            <Col className="gutter-row" span={12}>
              <Form.Item
                label="考试分数"
                name="testscore"
                rules={[
                  {
                    required: true,
                    message: "请输入考试分数",
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </Col>
          </Row>
          <Form.Item>
            <Button block shape="round" type="primary" htmlType="submit">
              确认
            </Button>
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};
export default Tstu;
